<?php

namespace app\forms\user;

use yii\db\Query;
use yii\db\Exception;
use yii\helpers\Json;
use app\forms\Model;
use app\models\Group;
use yii\web\HttpException;
use app\validators\PositiveInteger;

class ItemDataForm extends Model
{
    public $userId;
    public $itemId;

    public function rules()
    {
        return [
            ['userId', PositiveInteger::class],
            ['userId', 'required'],

            ['itemId', PositiveInteger::class],
            ['itemId', 'required'],
        ];
    }

    /**
     * @param $param
     * @return array
     * @throws HttpException
     */
    public static function getData($param)
    {
        $form = new self;
        $form->setAttributes($param);
        !$form->validate() ? $form->validateError() : '';

        try {

            // 查询当前用户权限下的部门数据
            $query = new Query;
            $query->select(['data']);
            $query->from('{{%user_item}}');
            $query->where(['user_id' => $form['userId'], 'item_id' => $form['itemId']]);
            $result = $query->one();
            !$result ? $form->serverError() : '';

            // 解析得到所有的id
            $arr = Json::decode($result['data']);
            $ids = !empty($arr) ? explode(',', $arr['ids']) : [];

            // 获取组织、部门树
            $group = (new Group)->getTreeForItemData($ids);
            return ['group' => $group];

        } catch (Exception $e) {
            $form->serverError();
        }
    }
}